package org.leo.dm.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

import org.leo.dm.util.ThreadPoolSingletonUtil;
import org.leo.dm.util.ThreadPoolUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * Created on 2015年11月5日
 * <p>
 * Description 线程池样例
 * <p>
 * Copyright neusoft (c) 2015 .
 * 
 * @author xiao_h
 *
 */
public class ThreadPoolUtilExample {
	static Logger log = LoggerFactory.getLogger(ThreadPoolUtilExample.class);

	public static void main(String[] args) {
		try {
			ThreadPoolUtil poolUtil = ThreadPoolSingletonUtil.getInstance();
			poolUtil.initPool(10);
			int threadPoolSize = poolUtil.getThreadPoolSize();
			log.info("初始化线程大小" + threadPoolSize);

			// 测试没有返回值的线程执行
			TestThreadRunnable tr = null;
			for (int i = 0; i < threadPoolSize; i++) {
				tr = new TestThreadRunnable();
				tr.setCount(i);
				poolUtil.getPool().execute(tr);
			}

			// 测试有返回值的线程执行
			List<Future<String>> resultList = new ArrayList<Future<String>>();
			TestThreadCallable tc = null;
			Future<String> future = null;
			for (int i = 0; i < threadPoolSize; i++) {
				tc = new TestThreadCallable();
				tc.setCount(i);
				future = poolUtil.getPool().submit(tc);
				resultList.add(future);
			}
			// 遍历任务的结果
			for (Future<String> fs : resultList) {
				log.info(fs.get());
			}

			poolUtil.shutdownPool();
			log.info("线程池关闭");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

/**
 * Runnable任务没有返回值
 * 
 * @author xiao_h
 * 
 */
class TestThreadRunnable implements Runnable {
	Logger log = LoggerFactory.getLogger(this.getClass());

	int count = 0;

	public void setCount(int count) {
		this.count = count;
	}

	public void run() {
		try {
			log.info("run()方法被自动调用，当前count " + count + " " + Thread.currentThread().getName() + "线程被调用了。");
			Thread.sleep(new Random().nextInt(1000));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

/**
 * Callable任务没有返回值
 * 
 * @author xiao_h
 * 
 */
class TestThreadCallable implements Callable<String> {
	Logger log = LoggerFactory.getLogger(this.getClass());

	int count = 0;

	public void setCount(int count) {
		this.count = count;
	}

	public String call() {
		try {
			log.info("call()方法被自动调用，当前count " + count + " " + Thread.currentThread().getName());

			Thread.sleep(new Random().nextInt(1000));
			if (new Random().nextBoolean()) {
				return "call()方法被自动调用，任务的结果是发生异常：" + Thread.currentThread().getName();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "call()方法被自动调用，任务的结果是正常结束 ：" + Thread.currentThread().getName();
	}
}
